using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using demo.Tool;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.IO;
using System.Linq;

namespace demo
{
    /// <summary>
    /// 消息推送客户端类
    /// 提供TCP连接、消息接收、消息处理等功能
    /// </summary>
    public class MessagePushClient
    {
        #region 私有字段
        private TcpClient client;
        private NetworkStream stream;
        private Thread receiveThread;
        private bool isConnected = false;
        private readonly object connectionLock = new object(); // 用于线程同步
        
        // UI控件引用（用于消息显示和状态更新）
        private ListBox lstMessages;
        private ToolStripStatusLabel statusLabel;
        private StatusStrip statusStrip;
        
        // 用户信息
        private UesrModel userData;
        #endregion

        #region 事件定义
        /// <summary>
        /// 消息接收事件
        /// </summary>
        public event Action<MessageModel> MessageReceived;

        /// <summary>
        /// 连接状态变更事件
        /// </summary>
        public event Action<string> ConnectionStatusChanged;

        /// <summary>
        /// 错误发生事件
        /// </summary>
        public event Action<string> ErrorOccurred;
        
        /// <summary>
        /// 门诊就诊信息接收事件
        /// </summary>
        public event Action<OutpatientVisitInfo> OutpatientInfoReceived;
        #endregion

        #region 属性
        /// <summary>
        /// 获取当前连接状态
        /// </summary>
        public bool IsConnected => isConnected;
        
        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        public UesrModel UserData => userData;
        #endregion

        #region 构造函数
        /// <summary>
        /// 初始化MessagePushClient实例
        /// </summary>
        /// <param name="messageListBox">用于显示消息的ListBox控件</param>
        /// <param name="statusLabel">用于显示状态的ToolStripStatusLabel控件</param>
        /// <param name="statusStrip">StatusStrip控件</param>
        /// <param name="userInfo">用户信息</param>
        public MessagePushClient(ListBox messageListBox, ToolStripStatusLabel statusLabel, StatusStrip statusStrip, UesrModel userInfo)
        {
            this.lstMessages = messageListBox ?? throw new ArgumentNullException(nameof(messageListBox));
            this.statusLabel = statusLabel ?? throw new ArgumentNullException(nameof(statusLabel));
            this.statusStrip = statusStrip ?? throw new ArgumentNullException(nameof(statusStrip));
            this.userData = userInfo ?? throw new ArgumentNullException(nameof(userInfo));
        }
        #endregion

        #region 公共方法
        /// <summary>
        /// 连接到服务器
        /// </summary>
        /// <param name="serverIp">服务器IP地址</param>
        /// <param name="port">服务器端口</param>
        /// <param name="username">用户名</param>
        public void ConnectToServer(string serverIp, int port, string username)
        {
            lock (connectionLock)
            {
                try
                {
                    operateLog.WriteLog("开始连接到消息推送服务器");
                    operateLog.WriteLog("服务器地址：" + serverIp + ":" + port);
                    operateLog.WriteLog("用户名：" + username);
                    
                    // 参数验证
                    if (string.IsNullOrEmpty(serverIp))
                    {
                        throw new ArgumentException("服务器IP地址不能为空");
                    }
                    if (port <= 0 || port > 65535)
                    {
                        throw new ArgumentException("端口号无效，必须在1-65535之间");
                    }
                    if (string.IsNullOrEmpty(username))
                    {
                        throw new ArgumentException("用户名不能为空");
                    }

                    // 确保之前的连接已断开
                    operateLog.WriteLog("断开之前的连接");
                    Disconnect();

                    // 保存用户名到userData
                    userData.user_id = username;

                    // 创建新的客户端实例
                    operateLog.WriteLog("创建TCP客户端实例");
                    client = new TcpClient();
                    
                    // 设置TCP客户端选项以提高稳定性
                    client.ReceiveTimeout = 30000; // 30秒接收超时
                    client.SendTimeout = 10000;    // 10秒发送超时
                    
                    // 连接到服务器
                    operateLog.WriteLog("开始异步连接到服务器");
                    IAsyncResult result = client.BeginConnect(serverIp, port, null, null);

                    // 设置连接超时（10秒，增加超时时间以提高稳定性）
                    bool success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(10));

                    if (!success)
                    {
                        operateLog.WriteLog("连接超时，取消连接操作");
                        client?.Close();
                        throw new TimeoutException("连接服务器超时，请检查网络连接和服务器状态");
                    }

                    // 完成连接
                    operateLog.WriteLog("完成异步连接");
                    client.EndConnect(result);
                    
                    // 验证连接状态
                    if (!client.Connected)
                    {
                        operateLog.WriteLog("TCP连接未成功建立");
                        throw new Exception("TCP连接未成功建立");
                    }

                    // 获取网络流
                    operateLog.WriteLog("获取网络流");
                    stream = client.GetStream();

                    // 验证流是否成功获取
                    if (stream == null)
                    {
                        operateLog.WriteLog("无法获取网络流");
                        throw new Exception("无法获取网络流");
                    }
                    
                    // 设置网络流的读写超时
                    stream.ReadTimeout = 30000;  // 30秒读取超时
                    stream.WriteTimeout = 10000; // 10秒写入超时

                    // 发送JSON格式的登录消息
                    operateLog.WriteLog("准备发送登录消息");
                    var loginMessage = new LoginMessage
                    {
                        Username = userData.user_id,
                        ClientInfo = new { Version = "1.0.0", Platform = "Windows" }
                    };
                    string jsonMessage = JsonConvert.SerializeObject(loginMessage);
                    byte[] usernameData = Encoding.UTF8.GetBytes(jsonMessage);
                    operateLog.WriteLog("登录消息内容：" + jsonMessage);

                    // 在写入前再次检查流
                    if (stream.CanWrite)
                    {
                        operateLog.WriteLog("发送登录消息到服务器");
                        stream.Write(usernameData, 0, usernameData.Length);
                        stream.Flush(); // 确保数据被发送
                        operateLog.WriteLog("登录消息发送完成");
                    }
                    else
                    {
                        operateLog.WriteLog("网络流不可写");
                        throw new Exception("网络流不可写");
                    }

                    isConnected = true;

                    // 启动接收消息的线程
                    operateLog.WriteLog("启动消息接收线程");
                    receiveThread = new Thread(ReceiveMessages);
                    receiveThread.IsBackground = true;
                    receiveThread.Name = "MessageReceiveThread";
                    receiveThread.Start();

                    string successMessage = string.Format("已连接到服务器 {0}:{1}", serverIp, port);
                    operateLog.WriteLog("连接成功：" + successMessage);
                    UpdateStatus(successMessage);
                    ConnectionStatusChanged?.Invoke("已连接");
                }
                catch (ArgumentException argEx)
                {
                    operateLog.WriteLog("连接参数错误：" + argEx.Message);
                    string errorMessage = "连接参数错误：" + argEx.Message;
                    UpdateStatus(errorMessage);
                    ErrorOccurred?.Invoke(errorMessage);
                    throw;
                }
                catch (TimeoutException timeEx)
                {
                    operateLog.WriteLog("连接超时：" + timeEx.Message);
                    Disconnect();
                    string errorMessage = "连接超时：" + timeEx.Message;
                    UpdateStatus(errorMessage);
                    ErrorOccurred?.Invoke(errorMessage);
                    throw;
                }
                catch (SocketException sockEx)
                {
                    operateLog.WriteLog("网络连接异常：" + sockEx.Message);
                    operateLog.WriteLog("Socket错误代码：" + sockEx.SocketErrorCode);
                    Disconnect();
                    string errorMessage = string.Format("网络连接失败：{0} (错误代码：{1})", sockEx.Message, sockEx.SocketErrorCode);
                    UpdateStatus(errorMessage);
                    ErrorOccurred?.Invoke(errorMessage);
                    throw new Exception(errorMessage, sockEx);
                }
                catch (Exception ex)
                {
                    operateLog.WriteLog("连接服务器时发生未知异常：" + ex.Message);
                    operateLog.WriteLog("异常类型：" + ex.GetType().Name);
                    operateLog.WriteLog("异常堆栈：" + ex.StackTrace);
                    
                    // 确保在异常发生时清理资源
                    Disconnect();

                    string errorMessage = string.Format("连接服务器失败: {0}", ex.Message);
                    UpdateStatus(errorMessage);
                    ErrorOccurred?.Invoke(errorMessage);
                    throw new Exception(errorMessage, ex);
                }
            }
        }

        /// <summary>
        /// 断开连接
        /// </summary>
        public void Disconnect()
        {
            lock (connectionLock)
            {
                try
                {
                    operateLog.WriteLog("开始断开消息推送服务器连接");
                    
                    if (!isConnected)
                    {
                        operateLog.WriteLog("连接状态已为断开，无需重复断开");
                        return;
                    }

                    isConnected = false;
                    operateLog.WriteLog("设置连接状态为断开");

                    var tempStream = stream;
                    var tempClient = client;
                    var tempThread = receiveThread;

                    stream = null;
                    client = null;
                    receiveThread = null;

                    // 优雅地关闭网络流
                    if (tempStream != null)
                    {
                        try
                        {
                            operateLog.WriteLog("关闭网络流");
                            if (tempStream.CanWrite)
                            {
                                tempStream.Flush(); // 确保所有数据都被发送
                            }
                            tempStream.Close();
                            tempStream.Dispose();
                            operateLog.WriteLog("网络流已关闭");
                        }
                        catch (Exception ex)
                        {
                            operateLog.WriteLog("关闭网络流时发生异常：" + ex.Message);
                        }
                    }

                    // 关闭TCP客户端
                    if (tempClient != null)
                    {
                        try
                        {
                            operateLog.WriteLog("关闭TCP客户端");
                            if (tempClient.Connected)
                            {
                                tempClient.GetStream()?.Close();
                            }
                            tempClient.Close();
                            operateLog.WriteLog("TCP客户端已关闭");
                        }
                        catch (Exception ex)
                        {
                            operateLog.WriteLog("关闭TCP客户端时发生异常：" + ex.Message);
                        }
                    }

                    // 优雅地停止接收线程
                    if (tempThread != null && tempThread.IsAlive)
                    {
                        try
                        {
                            operateLog.WriteLog("停止消息接收线程");
                            
                            // 首先尝试优雅地停止线程（等待2秒）
                            if (!tempThread.Join(2000))
                            {
                                operateLog.WriteLog("线程未在2秒内自然结束，尝试强制停止");
                                
                                // 如果线程没有在2秒内结束，则强制中断
                                try
                                {
                                    tempThread.Interrupt();
                                    if (!tempThread.Join(1000))
                                    {
                                        operateLog.WriteLog("线程未响应中断，使用Abort强制终止");
                                        tempThread.Abort();
                                        tempThread.Join(500);
                                    }
                                }
                                catch (Exception threadEx)
                                {
                                    operateLog.WriteLog("强制停止线程时发生异常：" + threadEx.Message);
                                }
                            }
                            
                            operateLog.WriteLog("消息接收线程已停止");
                        }
                        catch (Exception ex)
                        {
                            operateLog.WriteLog("停止接收线程时出错：" + ex.Message);
                            AddSystemMessage(string.Format("停止接收线程时出错: {0}", ex.Message));
                        }
                    }

                    operateLog.WriteLog("消息推送服务器连接断开完成");
                    UpdateStatus("已断开与服务器的连接");
                    ConnectionStatusChanged?.Invoke("已断开");
                }
                catch (Exception ex)
                {
                    operateLog.WriteLog("断开连接时发生未知异常：" + ex.Message);
                    operateLog.WriteLog("异常类型：" + ex.GetType().Name);
                    operateLog.WriteLog("异常堆栈：" + ex.StackTrace);
                    
                    string errorMessage = string.Format("断开连接时出错: {0}", ex.Message);
                    UpdateStatus(errorMessage);
                    ErrorOccurred?.Invoke(errorMessage);
                }
            }
        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 消息接收方法
        /// </summary>
        private void ReceiveMessages()
        {
            try
            {
                byte[] buffer = new byte[8192];
                int bytesRead;

                while (true)
                {
                    if (!isConnected)
                        break;

                    try
                    {
                        if (stream == null || !stream.CanRead)
                            break;

                        if (client.Available > 0)
                        {
                            bytesRead = stream.Read(buffer, 0, buffer.Length);
                            if (bytesRead > 0)
                            {
                                string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                                ProcessMessage(message);
                            }
                            else
                            {
                                throw new Exception("服务器关闭了连接");
                            }
                        }

                        Thread.Sleep(100);
                    }
                    catch (SocketException ex)
                    {
                        // 记录到日志或显示在界面上
                        AddSystemMessage(string.Format("接收消息时发生套接字错误: {0}", ex.SocketErrorCode));
                        break;
                    }
                    catch (Exception ex)
                    {
                        AddSystemMessage(string.Format("接收消息时发生错误: {0}", ex.Message));
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                AddSystemMessage(string.Format("消息接收线程异常: {0}", ex.Message));
            }
            finally
            {
                // 线程结束时断开连接
                if (isConnected)
                {
                    Disconnect();
                }
            }
        }

        /// <summary>
        /// 处理接收到的消息
        /// </summary>
        /// <param name="message">消息内容</param>
        private void ProcessMessage(string message)
        {
            try
            {
                // 将消息保存到日志文件
                SaveMessageToLog(message);
                
                // 尝试解析JSON消息
                //MessageBox.Show(message);
                var messageModel = JsonConvert.DeserializeObject<MessageModel>(message);
                
                if (messageModel == null)
                {
                    AddSystemMessage("收到格式错误的消息");
                    return;
                }

                // 处理不同类型的消息
                switch (messageModel.Type)
                {
                    case MessageType.LoginResponse:
                        ProcessLoginResponse(messageModel);
                        break;
                    case MessageType.Chat:
                        ProcessChatMessage(messageModel);
                        break;
                    case MessageType.Broadcast:
                        ProcessBroadcastMessage(messageModel);
                        break;
                    case MessageType.Error:
                        ProcessErrorMessage(messageModel);
                        break;
                    case MessageType.Heartbeat:
                        ProcessHeartbeatMessage(messageModel);
                        break;
                    case MessageType.UserStatusUpdate:
                        ProcessUserStatusUpdate(messageModel);
                        break;
                    default:
                        AddSystemMessage($"收到未知类型的消息: {messageModel.Type}");
                        break;
                }
                
                // 触发消息接收事件
                MessageReceived?.Invoke(messageModel);
            }
            catch (JsonException)
            {
                // 如果JSON解析失败，尝试处理旧格式的消息（向后兼容）
                ProcessLegacyMessage(message);
            }
            catch (Exception ex)
            {
                AddSystemMessage($"处理消息时发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新状态显示
        /// </summary>
        /// <param name="status">状态信息</param>
        private void UpdateStatus(string status)
        {
            if (statusStrip.InvokeRequired)
            {
                statusStrip.Invoke(new Action(() =>
                {
                    statusLabel.Text = status;
                }));
            }
            else
            {
                statusLabel.Text = status;
            }
        }

        /// <summary>
        /// 添加普通消息
        /// </summary>
        /// <param name="message">消息内容</param>
        private void AddMessage(string message)
        {
            if (lstMessages.InvokeRequired)
            {
                lstMessages.Invoke(new Action(() =>
                {
                    string timeStamp = DateTime.Now.ToString("HH:mm:ss");
                    lstMessages.Items.Add(string.Format("[{0}] {1}", timeStamp, message));
                    lstMessages.SelectedIndex = lstMessages.Items.Count - 1;
                }));
            }
            else
            {
                string timeStamp = DateTime.Now.ToString("HH:mm:ss");
                lstMessages.Items.Add(string.Format("[{0}] {1}", timeStamp, message));
                lstMessages.SelectedIndex = lstMessages.Items.Count - 1;
            }
        }

        /// <summary>
        /// 添加服务器消息
        /// </summary>
        /// <param name="message">消息内容</param>
        private void AddServerMessage(string message)
        {
            if (lstMessages.InvokeRequired)
            {
                lstMessages.Invoke(new Action(() =>
                {
                    string timeStamp = DateTime.Now.ToString("HH:mm:ss");
                    lstMessages.Items.Add(string.Format("[{0}] [服务器] {1}", timeStamp, message));
                    lstMessages.SelectedIndex = lstMessages.Items.Count - 1;
                }));
            }
            else
            {
                string timeStamp = DateTime.Now.ToString("HH:mm:ss");
                lstMessages.Items.Add(string.Format("[{0}] [服务器] {1}", timeStamp, message));
                lstMessages.SelectedIndex = lstMessages.Items.Count - 1;
            }
        }

        /// <summary>
        /// 添加广播消息
        /// </summary>
        /// <param name="message">消息内容</param>
        private void AddBroadcastMessage(string message)
        {
            if (lstMessages.InvokeRequired)
            {
                lstMessages.Invoke(new Action(() =>
                {
                    string timeStamp = DateTime.Now.ToString("HH:mm:ss");
                    lstMessages.Items.Add(string.Format("[{0}] [广播] {1}", timeStamp, message));
                    lstMessages.SelectedIndex = lstMessages.Items.Count - 1;
                }));
            }
            else
            {
                string timeStamp = DateTime.Now.ToString("HH:mm:ss");
                lstMessages.Items.Add(string.Format("[{0}] [广播] {1}", timeStamp, message));
                lstMessages.SelectedIndex = lstMessages.Items.Count - 1;
            }
        }

        /// <summary>
        /// 添加系统消息
        /// </summary>
        /// <param name="message">消息内容</param>
        private void AddSystemMessage(string message)
        {
            if (lstMessages.InvokeRequired)
            {
                lstMessages.Invoke(new Action(() =>
                {
                    lstMessages.Items.Add(string.Format("[系统] {0}", message));
                    lstMessages.SelectedIndex = lstMessages.Items.Count - 1;
                }));
            }
            else
            {
                lstMessages.Items.Add(string.Format("[系统] {0}", message));
                lstMessages.SelectedIndex = lstMessages.Items.Count - 1;
            }
        }
        #endregion

        #region 消息处理方法
        /// <summary>
        /// 处理登录响应消息
        /// </summary>
        /// <param name="message">消息模型</param>
        private void ProcessLoginResponse(MessageModel message)
        {
            try
            {
                var loginResponse = JsonConvert.DeserializeObject<LoginResponseMessage>(JsonConvert.SerializeObject(message));
                if (loginResponse.Success == true)
                {
                    AddSystemMessage($"登录成功: {loginResponse.Message}");
                    AddSystemMessage($"在线用户数: {loginResponse.OnlineUsers}");
                }
                else
                {
                    AddSystemMessage($"登录失败: {loginResponse.Error}");
                }
            }
            catch (Exception ex)
            {
                AddSystemMessage($"处理登录响应时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 处理聊天消息
        /// </summary>
        /// <param name="message">消息模型</param>
        private void ProcessChatMessage(MessageModel message)
        {
            try
            {
                var chatMessage = JsonConvert.DeserializeObject<ChatMessage>(JsonConvert.SerializeObject(message));
                
                // 检查消息是否是发给当前用户的
                if (string.IsNullOrEmpty(message.Receiver) || message.Receiver == userData.user_id)
                {
                    if (chatMessage.IsPrivate)
                    {
                        AddMessage($"[私聊] {message.Sender}: {chatMessage.Text}");
                    }
                    else
                    {
                        AddMessage($"{message.Sender}: {chatMessage.Text}");
                    }
                }
                else
                {
                    AddSystemMessage($"收到发给 {message.Receiver} 的消息，但当前用户是 {userData.user_id}");
                }
            }
            catch (Exception ex)
            {
                AddSystemMessage($"处理聊天消息时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 处理广播消息
        /// </summary>
        /// <param name="message">消息模型</param>
        private void ProcessBroadcastMessage(MessageModel message)
        {
            try
            {
                var broadcastMessage = JsonConvert.DeserializeObject<BroadcastMessage>(JsonConvert.SerializeObject(message));
                
                // 尝试解析特殊格式的内容（门诊就诊信息）
                if (!string.IsNullOrEmpty(message.Content) && message.Content.Contains("@") && message.Content.Contains("_"))
                {
                    // 解析特殊格式的内容
                    var outpatientInfo = OutpatientVisitInfo.Parse(message.Content);
                    if (outpatientInfo != null)
                    {
                        // 将解析后的对象存储到消息的Data属性中
                        broadcastMessage.Data = outpatientInfo;
                        
                        // 显示解析后的信息
                        AddBroadcastMessage($"收到就诊信息: {outpatientInfo.ToString()}");
                        
                        // 触发门诊就诊信息接收事件
                        OutpatientInfoReceived?.Invoke(outpatientInfo);
                    }
                    else
                    {
                        // 如果解析失败，显示原始内容
                        AddBroadcastMessage(broadcastMessage.Text ?? message.Content);
                    }
                }
                else
                {
                    // 处理普通广播消息
                    AddBroadcastMessage(broadcastMessage.Text ?? message.Content);
                }
            }
            catch (Exception ex)
            {
                AddSystemMessage($"处理广播消息时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 处理错误消息
        /// </summary>
        /// <param name="message">消息模型</param>
        private void ProcessErrorMessage(MessageModel message)
        {
            try
            {
                var errorMessage = JsonConvert.DeserializeObject<ErrorMessage>(JsonConvert.SerializeObject(message));
                AddSystemMessage($"[错误] {errorMessage.Error} (代码: {errorMessage.ErrorCode})");
            }
            catch (Exception ex)
            {
                AddSystemMessage($"处理错误消息时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 处理心跳消息
        /// </summary>
        /// <param name="message">消息模型</param>
        private void ProcessHeartbeatMessage(MessageModel message)
        {
            try
            {
                var heartbeatMessage = JsonConvert.DeserializeObject<HeartbeatMessage>(JsonConvert.SerializeObject(message));
                // 心跳消息通常不需要显示给用户，只记录到系统日志
                // AddSystemMessage($"收到心跳响应: {heartbeatMessage.ClientStatus}");
            }
            catch (Exception ex)
            {
                AddSystemMessage($"处理心跳消息时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 处理用户状态更新消息
        /// </summary>
        /// <param name="message">消息模型</param>
        private void ProcessUserStatusUpdate(MessageModel message)
        {
            try
            {
                var statusUpdate = JsonConvert.DeserializeObject<UserStatusUpdateMessage>(JsonConvert.SerializeObject(message));
                AddSystemMessage($"用户 {statusUpdate.Username} 状态更新为: {statusUpdate.Status} - {statusUpdate.StatusMessage}");
            }
            catch (Exception ex)
            {
                AddSystemMessage($"处理用户状态更新时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 处理旧格式消息（向后兼容）
        /// </summary>
        /// <param name="message">消息内容</param>
        private void ProcessLegacyMessage(string message)
        {
            try
            {
                // 消息格式: 目标用户|消息内容
                string[] parts = message.Split(new[] { '|' }, 2);
                if (parts.Length < 2)
                {
                    AddSystemMessage("收到格式错误的旧格式消息");
                    return;
                }

                string targetUser = parts[0];
                string content = parts[1];

                // 检查消息是否是发给当前用户的
                if (targetUser == userData.user_id)
                {
                    // 检查消息类型
                    if (content.StartsWith("SERVER|"))
                    {
                        // 服务器直接发送的消息
                        string serverMessage = content.Substring(7);
                        AddServerMessage(serverMessage);
                    }
                    else if (content.StartsWith("BROADCAST|"))
                    {
                        // 广播消息
                        string broadcastMessage = content.Substring(10);
                        AddBroadcastMessage(broadcastMessage);
                    }
                    else if (content.StartsWith("WELCOME|"))
                    {
                        // 欢迎消息
                        string welcomeMessage = content.Substring(8);
                        AddSystemMessage(welcomeMessage);
                    }
                    else
                    {
                        // 普通消息
                        AddMessage(content);
                    }
                    
                    // 为旧格式消息创建一个简单的MessageModel对象
                    var legacyMessageModel = new MessageModel
                    {
                        Type = MessageType.Chat,
                        Content = content,
                        Receiver = targetUser,
                        Sender = "Unknown"
                    };
                    
                    // 触发消息接收事件
                    MessageReceived?.Invoke(legacyMessageModel);
                }
                else
                {
                    // 不是发给当前用户的消息（可能是误传）
                    AddSystemMessage("收到发给 " + targetUser + " 的消息，但当前用户是 " + userData.user_id);
                }
            }
            catch (Exception ex)
            {
                AddSystemMessage($"处理旧格式消息时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 发送JSON消息
        /// </summary>
        /// <param name="messageModel">消息模型</param>
        public void SendMessage(MessageModel messageModel)
        {
            try
            {
                if (!isConnected || stream == null)
                {
                    throw new Exception("未连接到服务器");
                }

                string jsonMessage = JsonConvert.SerializeObject(messageModel);
                byte[] data = Encoding.UTF8.GetBytes(jsonMessage);
                stream.Write(data, 0, data.Length);
            }
            catch (Exception ex)
            {
                string errorMessage = $"发送消息失败: {ex.Message}";
                AddSystemMessage(errorMessage);
                ErrorOccurred?.Invoke(errorMessage);
            }
        }

        /// <summary>
        /// 发送聊天消息
        /// </summary>
        /// <param name="text">消息文本</param>
        /// <param name="isPrivate">是否私聊</param>
        /// <param name="targetUser">目标用户（私聊时必填）</param>
        public void SendChatMessage(string text, bool isPrivate = false, string targetUser = null)
        {
            var chatMessage = new ChatMessage
            {
                Text = text,
                IsPrivate = isPrivate,
                TargetUser = targetUser,
                Sender = userData.user_id
            };
            SendMessage(chatMessage);
        }

        /// <summary>
        /// 发送心跳消息
        /// </summary>
        public void SendHeartbeat()
        {
            var heartbeatMessage = new HeartbeatMessage
            {
                ClientStatus = "alive",
                Sender = userData.user_id
            };
            SendMessage(heartbeatMessage);
        }
        #endregion

        #region 日志功能
        /// <summary>
        /// 将消息保存到日志文件
        /// </summary>
        /// <param name="message">消息内容</param>
        private void SaveMessageToLog(string message)
        {
            try
            {
                // 确保Logs目录存在
                string logsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
                if (!Directory.Exists(logsDirectory))
                {
                    Directory.CreateDirectory(logsDirectory);
                }

                // 创建日志文件名（按日期分文件）
                string logFileName = Path.Combine(logsDirectory, $"ServerMessages_{DateTime.Now.ToString("yyyy-MM-dd")}.log");

                // 获取当前时间戳
                string timeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

                // 组织日志内容
                string logContent = $"[{timeStamp}] {message}{Environment.NewLine}";

                // 追加写入日志文件
                File.AppendAllText(logFileName, logContent);
            }
            catch (Exception ex)
            {
                // 日志记录失败，在UI上显示错误
                AddSystemMessage($"保存消息日志时出错: {ex.Message}");
            }
        }
        #endregion
    }
}